<?php
declare (strict_types = 1);

namespace app\home\controller;

use app\base\BaseController;
use app\home\validate\EnterpriseCheck;
use app\home\validate\GoodsCheck;
use app\home\validate\GoodsCollarCheck;
use app\home\validate\ItemCheck;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class GoodsCollar extends BaseController
{
    /**
     * 商品领用记录管理
     */
    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = array();

            $eid = !empty($param['eid']) ? $param['eid']: $this->eid;

            if($eid > 0){
                $where[] = ['eid' , '=' , $eid];
            }

            $where[] = ['status', '>=', 0];
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $content = Db::name('GoodsBatch')
                ->order('eid asc,create_time desc')
                ->where($where)
                ->paginate($rows, false, ['query' => $param])->toArray();

            foreach($content['data'] as $key => &$value){

                //出库时间
                $value['fmt_out_time'] = !empty($value['out_time']) && $value['out_time'] > 0 ? date('Y-m-d H:i:s' , $value['out_time']) : '' ;
                //所属企业
                $deparment = Db::name('Enterprise')->where(['id'=>$value['eid']])->find();
                $value['d_name'] = $deparment['title'] ?? '系统管理员';
                //所属员工
                $user = Db::name('User')->where(['id'=>$value['uid']])->find();
                $value['use_user'] = $user['name'] ?? '';
                //所属项目
                $item = Db::name('Item')->where(['id'=>$value['item_id']])->find();
                $value['item_name'] = $item['name'] ?? '';

            }
            return table_assign(0, '', $content);
        } else {

            return view();
        }
    }

    /**
     * 获取分页商品
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPageGoods(){
        $param = get_params();
        $where = array();

        $eid = !empty($param['eid']) ? $param['eid']: $this->eid;

        $where[] = ['eid' , '=' , $eid];

        if (!empty($param['name'])) {
            $where[] = ['name', 'like', '%' . $param['name'] . '%'];
        }

        if (!empty($param['out_code'])) {
            $where[] = ['out_code', '=', $param['out_code']];
        }

        $where[] = ['status', '>=', 0];
//        $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
        $content = Db::name('Goods')
            ->order('create_time desc')
            ->where($where)
            ->select()->toArray();

        foreach($content as $key => &$value){

            $value['all_price'] = round($value['num'] * $value['price'] , 2);
        }
        $list['data'] = $content;

        return table_assign(0, '', $list);
    }

    /**
     * 获取分页商品
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPageItem(){

        $param = get_params();

        $eid = !empty($param['eid']) ? $param['eid']: $this->eid;

        $where[] = ['eid' , '=' , $eid];
        $where[] = ['status', '>=', 0];

        $content = Db::name('Item')
            ->order('create_time desc')
            ->where($where)
            ->select()->toArray();

        return to_assign(0, '', $content);
    }


    /**
     * 获取分页员工
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPageUser(){

        $param = get_params();

        $eid = !empty($param['eid']) ? $param['eid']: $this->eid;

        $where[] = ['eid' , '=' , $eid];
        $where[] = ['status', '>=', 0];

        $content = Db::name('User')
            ->order('create_time desc')
            ->where($where)
            ->select()->toArray();

        return to_assign(0, '', $content);
    }

    /**
     *领取商品
     */
    public function add()
    {
        $param = get_params();
        $eid = !empty($param['eid']) ? $param['eid']: $this->eid;

        if (request()->isAjax()) {
            try {
                validate(GoodsCollarCheck::class)->scene('add')->check($param);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return to_assign(1, $e->getError());
            }

            $data = [];
            $goods = $param['goods'];

            $c_time = time();

            Db::startTrans();


            //添加领取物料批次
            $batch = [
                'uid' => $param['uid'],
                'eid' => $eid,
                'item_id' => $param['item_id'],
                'num' => $param['num'],
                'money' => $param['money'],
                'out_code' => $param['out_code'],
                'remark' => $param['out_code'] ?? '',
                'out_time'   => strtotime($param['out_time']),
                'out_year'   => date('Y',strtotime($param['out_time'])),
                'out_month'  => date('m',strtotime($param['out_time'])),
                'create_time' => $c_time,
                'c_time' => $c_time,
            ];

            $gb_id = Db::name('GoodsBatch')->strict(false)->field(true)->insertGetId($batch);

            foreach($goods as $key =>$value){

                $info = [];
                $info['good_id']    = $value['good_id'];
                $info['item_id']    = $param['item_id'];
                $info['gb_id']      = $gb_id;
                $info['name']       = $value['name'];
                $info['num']        = $value['num'];
                $info['price']      = $value['price'];
                $info['money']      = round($value['num'] * $value['price'] , 2);
                $info['eid']        = $eid;
                $info['c_time']     = $c_time;
                $info['create_time']     = $c_time;
                $info['out_time']   = strtotime($param['out_time']);
                $info['uid']        = $param['uid'];
                $info['out_code']   = $param['out_code'];
                $info['remark']     = $param['remark'] ?? '';
                $info['out_year']   = date('Y',strtotime($param['out_time']));
                $info['out_month']  = date('m',strtotime($param['out_time']));

                $data[] = $info;

                //根据当前物品的库存
                $good = Db::name('goods')->where('id' , '=' , $value['good_id'])->find();

                if($value['num'] > $good['num']){
                    DB::rollback();
                    return to_assign(1 , '领取数量不能大于商品库存');
                }

                Db::name('goods')->where(['id' => $value['good_id']])->dec('num' , (float)$value['num'])->update();

            }

            $res = Db::name('GoodsCollar')->strict(false)->field(true)->insertAll($data);
            if ($res) {
                Db::commit();
                add_log('add', '', $param);
            }else{
                DB::rollback();
            }
            return to_assign();
        }else {

            return view();

        }
    }


    public function info(){
        $param = get_params();
        $id = $param['id'];
        $goodsBatch = Db::name('GoodsBatch')
            ->order('eid asc,create_time desc')
            ->where('id',$id)
            ->find();
        //出库时间
        $outTime = !empty($goodsBatch['out_time']) && $goodsBatch['out_time'] > 0 ? date('Y-m-d' , $goodsBatch['out_time']) : '' ;
        //所属员工
        $user = Db::name('User')->where(['id'=>$goodsBatch['uid']])->find();
        $userName = $user['name'] ?? '';
        //所属部门
        $department = Db::name('EnterpriseDepartment')->where(['id'=>$user['did']])->find();
        $depName = $department['title'] ?? '';
        //所属企业
        $enterprise = Db::name('Enterprise')->where(['id'=>$goodsBatch['eid']])->find();
        $entName = $enterprise['title'] ?? '系统管理员';
        View::assign('outTime', $outTime);
        View::assign('userName', $userName);
        View::assign('depName', $depName);
        View::assign('entName', $entName);
        View::assign('outCode',$goodsBatch['out_code']);
        if (request()->isAjax()) {
            $where['gb_id']  = $id;
            $where[] = ['status', '>=', 0];
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $content['data'] = Db::name('GoodsCollar')
                ->order('id asc')
                ->where($where)
                ->select()->toArray();
//                ->paginate($rows, false, ['query' => $param])->toArray();

            if(!empty($content)){
                foreach($content['data'] as $key => &$value){
                    $value['number'] = $key + 1;
                    //所属物品
                    $good = Db::name('Goods')->where(['id'=>$value['good_id']])->find();
                    $value['version'] = $good['version'] ?? '';
                    $value['unit'] = $good['unit'] ?? '';
                    $value['code'] = $good['code'] ?? '';
                }
            }
            return table_assign(0, '', $content);
        } else {
            return view();
        }

    }


    //删除
    public function delete()
    {
        $id = get_params("id");
        $data['status'] = '-1';
        $data['id'] = $id;
        $data['update_time'] = time();
        $data['delete_time'] = time();
        Db::startTrans();
        $res = Db::name('GoodsBatch')->update($data);

        $info['status'] = '-1';
        $info['update_time'] = time();
        $info['delete_time'] = time();
        $info_res = Db::name('GoodsCollar')->where(['gb_id' => $id])->update($info);

        if ($res !== false && $info_res !== false) {
            add_log('delete', $id, $data);
            Db::commit();
            return to_assign(0, "删除成功");
        } else {
            Db::rollback();
            return to_assign(1, "删除失败");
        }
    }


}
